import multiprocessing

import pymysql
from copy import copy


class LocationNumber:
    connection = None
    user = 'root'
    password = ''
    db_name = 'cqssc'
    host = 'localhost'
    cursor = None
    column_map = {'zero': 1, 'one': 1, 'two': 1, 'three': 1,
                  'four': 1, 'five': 1, 'six': 1, 'seven': 1,
                  'eight': 1, 'night': 1
                  }
    column_key_map = tuple()
    table_name = "first_number"
    big = {"0": 0, "1": 0, "2": 0, "3": 0, "4": 0, "5": 1, "6": 1, "7": 1, "8": 1, "9": 1}
    odd = {"0": 0, "1": 1, "2": 0, "3": 1, "4": 0, "5": 1, "6": 0, "7": 1, "8": 0, "9": 1}
    location = 0

    def __init__(self,location,table):
        self.connection = pymysql.connect(self.host, self.user, self.password, self.db_name)
        self.cursor = self.connection.cursor()
        self.column_key_map = tuple(self.column_map.keys())
        self.location = int(location) - 1
        self.table_name = table

    """
        判断是否有这个开奖数据
    """
    def hasPeriod(self, period):
        self.cursor = self.connection.cursor(cursor=pymysql.cursors.DictCursor)
        has_period_sql = r"select * from `{TABLE_NAME}` where period = %s".format(TABLE_NAME=self.table_name)
        self.cursor.execute(has_period_sql, (period,))
        result = self.cursor.fetchone()

        if result is None:
            return False
        else:
            return result

    def merge(self, period, column_map):
        period = period.split("-")
        number = int(period[1]) - 1

        if number > 0:
            period[1] = str(number).zfill(3)

        pre_period = "-".join(period)
        pre_data = self.hasPeriod(pre_period)

        if pre_data:
            for key, item in pre_data.items():
                if key in column_map:
                    column_map[key] += item

        return column_map

    def is_big(self,num):
        num = str(num)
        return self.big[num]

    def is_odd(self,num):
        num = str(num)
        return self.odd[num]

    def insert(self, lottery_data):
        column_map = copy(self.column_map)
        column_map = self.merge(lottery_data['period'], column_map)
        column_map['period'] = lottery_data['period']
        column_map['number'] = lottery_data['number']
        first_num = int(column_map['number'][self.location])
        column_map['first_number'] = first_num
        column_map['big'] = self.is_big(first_num)
        column_map['odd'] = self.is_odd(first_num)
        print("第{location}位分析：{num}".format(location=self.location+1,num=first_num))

        if first_num <= len(self.column_key_map):
            key_transform = self.column_key_map[first_num]
            column_map[key_transform] = 0

        sql_values = tuple(column_map.values())
        insert_sql = r"insert into `{TABLE_NAME}`(`zero`,`one`,`two`,`three`,`four`,`five`,`six`," \
                     r"`seven`,`eight`,`night`,`period`,`number`,`current_number`,`odd`,`big`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        try:
            self.cursor.execute(insert_sql.format(TABLE_NAME=self.table_name), args=sql_values)
            self.connection.commit()
            del column_map
            return self.cursor.lastrowid
        except Exception as e:
            self.connection.rollback()
            print(e)
            return False

    def close(self):
        self.cursor.close()
        self.connection.close()


# class testinsert:
#
#     def insert(self,lottery_data):
#         fn = FirstNumber()
#         fn.insert(lottery_data)
#
#
#     def run(self):
#         test = {"period": "170604-002", "number": "56789"}
#         first_process = multiprocessing.Process(target=self.insert, args=(test,))
#         first_process.start()

# if __name__ == "__main__":
#     pass
    # multiprocessing.freeze_support()
    # test = testinsert()
    # test.run()
    # ln.hasPeriod(period="170604-002")
    # ln.insert({"period": "170604-002", "number": "56789"})
